package com.eco.fanliapp.job.goodsjob;


import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.SyUserCollectionMapper;
import com.eco.fanliapp.entity.SyUserCollection;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.vo.respone.ResponeResults;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;

/**
 * 收藏商品同步到数据库
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class CollectionTask implements Job, Serializable {


    private static final Logger log = LoggerFactory.getLogger(CollectionTask.class);

    @Autowired
    private IUserCashschemeService userCashschemeService;
    @Autowired
    private IAppGoodsService appGoodsService;
    @Autowired
    private ITaoBaoService iTaoBaoService;

    @Autowired
    private SyUserCollectionMapper syUserCollectionMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private ISyUserCollectionService syUserCollectionService;

    public CollectionTask() {
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long startTime = System.currentTimeMillis();
        log.info("***************************************收藏商品同步到数据库 CollectionTask：executeCount=" + executeCount + "--startTime=" + startTime);

        try {
            String save_update_key = "app_user_collection_saveOrUpdate";
            List<SyUserCollection> Collections = new ArrayList<>();
            if (redisTemplate.hasKey(save_update_key)) {
                Map<String, String> itemMap = (Map) redisTemplate.opsForValue().get(save_update_key);
                for (String itemkey : itemMap.keySet()) {
                    String[] split = itemkey.split(":");
                    String itemId = split[1];
                    String userId = split[0];
                    SyUserCollection collection = syUserCollectionMapper.selectCollection(userId, itemId);
                    SyUserCollection syUserCollection = collectionList(itemId, Long.valueOf(userId));
                    if (syUserCollection != null) {
                        if ("0".equals(itemMap.get(itemkey))) {
                            syUserCollection.setDeleted(1);
                        } else {
                            syUserCollection.setDeleted(0);
                        }

                        if (collection == null) {
                            Collections.add(syUserCollection);
                        } else {
                            syUserCollection.setTableId(collection.getTableId());
                            Collections.add(syUserCollection);
                        }
                    }
                }
            }
            // 更新到数据库
            if (Collections.size() > 0) {
                Boolean i = syUserCollectionService.saveOrUpdateBatch(Collections);
                if (i) {
                    redisTemplate.delete(save_update_key);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("收藏商品同步到数据库失败 ");
        }
        long endTime = System.currentTimeMillis();
        log.info("***************************************结束收藏商品同步到数据库 CollectionTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startTime));

    }

    public SyUserCollection collectionList(String itemId, Long userId) {
        ServerResponse<ResponeResults> response = iTaoBaoService.getHdkSearchItemIdDetail(itemId, userId, null, "0", 1,null);
        if (response.getStatus() == 200 && response.getData() != null) {
            List<ResponeResults.DataBean> dataBeans = response.getData().getData();
            if (dataBeans != null && dataBeans.size() == 1) {
                for (ResponeResults.DataBean bean : dataBeans) {
                    SyUserCollection syUserCollection = new SyUserCollection();
                    syUserCollection.setGoodsId(Long.valueOf(itemId));
                    syUserCollection.setUserId(userId);
                    if (bean.getItemShortTitle().isEmpty() || bean.getItemShortTitle().equals("")) {
                        syUserCollection.setGoodsName(bean.getItemTitle());
                    }
                    syUserCollection.setGoodsName(bean.getItemShortTitle());
                    syUserCollection.setGoodsPicture(bean.getItempictUrl());
                    syUserCollection.setGoodsCoupon(new BigDecimal(bean.getCouponMoney()));
                    syUserCollection.setGoodsPrice(new BigDecimal(bean.getItemPrice()));
                    syUserCollection.setGoodsSubsidies(bean.getFanliMoney());
                    syUserCollection.setBelongDate(new Date());
                    syUserCollection.setGoodsTkPrice(bean.getTheirPriceMoney());
                    if (bean.getItemType().equalsIgnoreCase("B")) {
                        //2天猫
                        syUserCollection.setGoodsShopType(2);
                    } else {
                        //1淘宝
                        syUserCollection.setGoodsShopType(1);
                    }
                    syUserCollection.setEnable(1);


                    return syUserCollection;
                }
            }
        }
        return null;
    }
}
